package com.commonEncryptionAlgorithms.hashFunction.hash.md5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5E2 {
    private static final String MD5STR = "MD5";

    public static String getMD5(String input) {
        try {
            // 获取MD5 MessageDigest实例
            MessageDigest md = MessageDigest.getInstance(MD5STR);
            // 计算MD5散列值
            byte[] hashBytes = md.digest(input.getBytes());
            // 将散列值转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }

    // 新增方法用于获取byte数组的MD5散列值
    public static String getMD5(byte[] inputBytes) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD5STR);
            byte[] hashBytes = md.digest(inputBytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }
}
